#include "AppConfig.h"
#include <QMutex>
#include <QSettings>
#include <QString>
#include <QDebug>
#include "utils/QUIUtils.h"
#include "log.h"
#include "AppConfigConstants.h"


AppConfig &AppConfig::getInstance()
{
    static QMutex mutex;
    QMutexLocker locker(&mutex);  // 确保线程安全
    static AppConfig instance;
    return instance;
}

void AppConfig::UpdatData()
{
    emit sigDataChange();
}

bool AppConfig::loadConfig()
{
    if (!settings) {
        qWarning() << "Settings not initialized!";
        return false;
    }

    try {
        // 加载字体配置
        if (!loadFontConfig()) {
            warningLog()<<"Failed to load font configuration.";
        }

        // 加载计时器配置
        if (!loadTimerConfig()) {
            warningLog()<<"Failed to load timer configuration.";
        }

        // 加载背景设置
        if (!loadBackgroundSettings()) {
            warningLog()<<"Failed to load background settings.";
        }

        // 加载其他设置
        if (!loadSettings()) {
            warningLog()<<"Failed to load playback settings.";
        }

        // 加载超时动作设置
        if (!loadTimeoutAction()) {
            warningLog()<<"Failed to load timeout action settings.";
        }

        // 加载声音设置
        if (!loadSoundSettings()) {
            warningLog()<<"Failed to load sound settings.";
        }
        // 加载声音设置
        if (!loadUserInfoSettings()) {
            warningLog()<<"Failed to load sound settings.";
        }

        // 加载声音设置
        if (!loadTimeFormatSettings()) {
            warningLog()<<"Failed to load time format settings.";
        }

        // [FDD-2025-03-015] 加载任务面板状态
        if (!loadTaskPanelSettings()) {
            warningLog()<<"Failed to load task panel settings.";
        }

        return true;  // 所有配置项加载成功
    } catch (...) {
        warningLog() << "Failed to load configuration due to an unexpected error.";
        return false;  // 捕获异常，加载失败
    }
}

bool AppConfig::saveConfig() const
{
    if (!settings) {
        qWarning() << "Settings not initialized!";
        return false;
    }

    try {
        // 保存字体配置
        if (!saveFontConfig()) {
            logWarning("Failed to save font configuration.");
        }

        // 保存计时器配置
        if (!saveTimerConfig()) {
            logWarning("Failed to save timer configuration.");
        }

        // 保存背景设置
        if (!saveBackgroundSettings()) {
            logWarning("Failed to save background settings.");
        }

        // 保存其他设置
        if (!saveSettings()) {
            logWarning("Failed to save playback settings.");
        }

        // 保存超时动作设置
        if (!saveTimeoutAction()) {
            logWarning("Failed to save timeout action settings.");
        }

        // 保存声音设置
        if (!saveSoundSettings()) {
            logWarning("Failed to save sound settings.");
        }

        // 保存声音设置
        if (!saveUserInfoSettings()) {
            logWarning("Failed to save user info settings.");
        }

        // 保存声音设置
        if (!saveTimeFormatSettings()) {
            logWarning("Failed to save time format settings.");
        }

        // [FDD-2025-03-015] 保存任务面板状态
        if (!saveTaskPanelSettings()) {
            logWarning("Failed to save task panel settings.");
        }

        return true;  // 所有配置项保存成功
    } catch (...) {
        warningLog() << "Failed to save configuration due to an unexpected error.";
        return false;  // 捕获异常，保存失败
    }
}


void AppConfig::setEncryptionEnabled(bool enabled)
{
    encryptionEnabled = enabled;
}

void AppConfig::onDataChange()
{
    saveConfig();
    emit sigDataChange();
}

AppConfig::AppConfig(QObject *parent)
    : QObject{parent}, settings(nullptr), encryptionEnabled(false)
{
    m_strFilePath = QUIUtils::appPath() + "/config/setting.ini";

    reateConfigFileIfNotExist();

    const QByteArray encryptionKey = "1314520";

    initSettings(encryptionKey);

    loadConfig();
}

AppConfig::~AppConfig()
{
    saveConfig();
}

void AppConfig::reateConfigFileIfNotExist()
{
    // 检查配置文件是否存在
    QFile configFile(m_strFilePath);

    if (!configFile.exists()) {
        infoLog() << "Config file does not exist, creating it...";

        // 尝试创建文件所在的目录（如果目录不存在）
        QDir dir(QFileInfo(m_strFilePath).absolutePath());
        if (!dir.exists()) {
            dir.mkpath(QFileInfo(m_strFilePath).absolutePath());
        }

        // 打开文件，准备写入
        if (!configFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
            warningLog() << "Failed to create config file!";
            return;
        }

        QTextStream out(&configFile);

        // 写入字体设置
        out << "[" << GROUP_FONT_SETTINGS << "]\n";
        out << KEY_FONT_FAMILY << "=default\n";
        out << KEY_FONT_SIZE << "=10\n";
        out << KEY_FONT_BOLD << "=false\n";
        out << KEY_FONT_ITALIC << "=false\n";
        out << KEY_FONT_UNDERLINE << "=false\n";

        // 写入计时器配置
        out << "[" << GROUP_TIMER_SETTINGS << "]\n";
        out << KEY_TIMER_ENABLED << "=false\n";
        out << KEY_TIMER_MODE << "=0\n";
        out << KEY_TIMER_DURATION << "= 300000\n";
        out << KEY_TIMER_ALARM1 << "=0\n";
        out << KEY_TIMER_ALARM2 << "=0\n";
        out << KEY_TIMER_ALARM3 << "=0\n";
        out << KEY_TIMER_TIMEOUT << "=0\n";
        out << KEY_TIMER_CONTINUOUS_REMINDER << "=false\n";

        // 写入计时器配置
        out << "[" << GROUP_FORMAT_TYPE_SETTINGS << "]\n";
        out << KEY_FORMAT_TYPE << "= 2\n";

        // 写入背景设置
        out << "[" << GROUP_BACKGROUND_SETTINGS << "]\n";
        out << KEY_BG_TRANSPARENT << "=false\n";
        out << KEY_BG_FILE_PATH << "=\n";
        out << KEY_BG_RADIUS << "=0\n";

        // 写入回放设置
        out << "[" << GROUP_PLAYBACK_SETTINGS << "]\n";
        out << KEY_PLAYBACK_SMART_TIMING << "=false\n";
        out << KEY_PLAYBACK_TIMELY_SETTING << "=false\n";
        out << KEY_PLAYBACK_PAUSE_TIMING << "=false\n";
        out << KEY_PLAYBACK_NO_SWITCH_TIME << "=false\n";
        out << KEY_PLAYBACK_HIDE_NOT_TIMING << "=false\n";
        out << KEY_PLAYBACK_DUAL_SCREEN << "=false\n";

        // 写入超时动作设置
        out << "[" << GROUP_TIMEOUT_ACTION_SETTINGS << "]\n";
        out << KEY_TIMEOUT_ACTION_TYPE << "=0\n";
        out << KEY_TIMEOUT_SCREEN_ACTION << "=1\n";

        // 写入声音设置
        out << "[" << GROUP_SOUND_SETTINGS << "]\n";
        out << KEY_SOUND_START_FILE_PATH << "=\n";
        out << KEY_SOUND_START_ENABLED << "=true\n";
        out << KEY_SOUND_START_FLASHING << "=false\n";
        out << KEY_SOUND_START_TEXT_VISIBLE << "=true\n";

        // 写入应用程序设置
        out << "[" << GROUP_APP_SETTINGS << "]\n";
        out << KEY_APP_MAC_ADDRESS << "=\n";
        out << KEY_APP_PERMISSION_LEVEL << "=0\n";
        out << KEY_APP_ACTIVATION_DURATION << "=0\n";
        out << KEY_APP_SN << "= 20240520\n";

        // 写入后关闭文件
        configFile.close();
        infoLog() << "Config file created and default settings written.";

        // 加载配置文件
        loadConfig();
    } else {
        warningLog() << "Config file already exists.";
    }
}
void AppConfig::initSettings(const QByteArray& encryptionKey)
{
    settings = new QSettings(m_strFilePath, QSettings::IniFormat);

    this->encryptionKey = QCryptographicHash::hash(encryptionKey, QCryptographicHash::Sha256); // 使用SHA-256哈希作为加密密钥
}

QVariant AppConfig::loadSetting(const QString& group, const QString &key, const QVariant &defaultValue) const
{
    settings->beginGroup(group);
    QByteArray value = settings->value(key, defaultValue).toByteArray();
    settings->endGroup();
    if (encryptionEnabled) {
        return QVariant(decrypt(value));
    } else {
        return QVariant(value);
    }
}

void AppConfig::saveSetting(const QString& group, const QString &key, const QVariant &value) const
{
    QByteArray data;

    if (value.canConvert<QByteArray>()) {
        data = value.toByteArray();
    } else {
        // 如果无法直接转换，使用字符串形式
        data = value.toString().toUtf8();
    }

    if (encryptionEnabled) {
        data = encrypt(data);
    }
    settings->beginGroup(group);
    settings->setValue(key, data);
    settings->endGroup();
    // 日志记录或调试信息（可选）
    debugLog() << "Saved setting:" << group<<"/"<< key << "=" << (encryptionEnabled ? "[ENCRYPTED]" : data);
}

bool AppConfig::loadFontConfig()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    QString fontFamily = loadSetting(GROUP_FONT_SETTINGS,KEY_FONT_FAMILY, "default").toString();
    int fontSize = loadSetting(GROUP_FONT_SETTINGS,KEY_FONT_SIZE, 10).toInt();
    bool isBold = loadSetting(GROUP_FONT_SETTINGS,KEY_FONT_BOLD, false).toBool();
    bool isItalic = loadSetting(GROUP_FONT_SETTINGS,KEY_FONT_ITALIC, false).toBool();
    bool isUnderline = loadSetting(GROUP_FONT_SETTINGS,KEY_FONT_UNDERLINE, false).toBool();

    // 设置字体属性
    _font.setFamily(fontFamily);
    _font.setPointSize(fontSize);
    _font.setBold(isBold);
    _font.setItalic(isItalic);
    _font.setUnderline(isUnderline);

    return true;
}

bool AppConfig::saveFontConfig() const
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }
    saveSetting(GROUP_FONT_SETTINGS,KEY_FONT_FAMILY, _font.family());
    saveSetting(GROUP_FONT_SETTINGS,KEY_FONT_SIZE, _font.pointSize());
    saveSetting(GROUP_FONT_SETTINGS,KEY_FONT_BOLD, _font.bold());
    saveSetting(GROUP_FONT_SETTINGS,KEY_FONT_ITALIC, _font.italic());
    saveSetting(GROUP_FONT_SETTINGS,KEY_FONT_UNDERLINE, _font.underline());
    return true;
}

bool AppConfig::loadTimerConfig()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }
    _timerConfig.isTimerEnabled = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ENABLED, false).toBool();
    _timerConfig.mode = static_cast<TimerMode>(loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_MODE, 0).toInt());
    _timerConfig.durationMs = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_DURATION, 0).toInt();
    _timerConfig.alarm1Ms = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM1, 0).toInt();
    _timerConfig.isAlarm1Enabled = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM1_ENABLE, false).toBool();
    _timerConfig.alarm2Ms = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM2, 0).toInt();
    _timerConfig.isAlarm2Enabled = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM2_ENABLE, false).toBool();
    _timerConfig.alarm3Ms = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM3, 0).toInt();
    _timerConfig.isAlarm3Enabled = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM3_ENABLE, false).toBool();
    _timerConfig.timeoutMs = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_TIMEOUT, 0).toInt();
    _timerConfig.isTimeoutEnabled = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_TIMEOUT_ENABLE, false).toBool();
    _timerConfig.isContinuousReminder = loadSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_CONTINUOUS_REMINDER, false).toBool();
    return true;
}

bool AppConfig::saveTimerConfig() const
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ENABLED, _timerConfig.isTimerEnabled);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_MODE, static_cast<int>(_timerConfig.mode));
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_DURATION, _timerConfig.durationMs);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM1, _timerConfig.alarm1Ms);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM1_ENABLE, _timerConfig.isAlarm1Enabled);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM2, _timerConfig.alarm2Ms);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM2_ENABLE, _timerConfig.isAlarm2Enabled);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM3, _timerConfig.alarm3Ms);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_ALARM3_ENABLE, _timerConfig.isAlarm3Enabled);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_TIMEOUT, _timerConfig.timeoutMs);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_TIMEOUT_ENABLE, _timerConfig.isTimeoutEnabled);
    saveSetting(GROUP_TIMER_SETTINGS,KEY_TIMER_CONTINUOUS_REMINDER, _timerConfig.isContinuousReminder);

    return true;
}

bool AppConfig::saveBackgroundSettings() const
{
    if (!this->settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    saveSetting(GROUP_BACKGROUND_SETTINGS, KEY_BG_TRANSPARENT, _bgSettings.isTransparent);
    saveSetting(GROUP_BACKGROUND_SETTINGS, KEY_BG_FILE_PATH, _bgSettings.filePath);
    saveSetting(GROUP_BACKGROUND_SETTINGS, KEY_BG_RADIUS, _bgSettings.radius);

    return true;
}

bool AppConfig::loadBackgroundSettings()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false; // 返回默认构造的BackgroundSettings
    }

    _bgSettings.isTransparent = loadSetting(GROUP_BACKGROUND_SETTINGS, KEY_BG_TRANSPARENT, false).toBool();
    _bgSettings.filePath = loadSetting(GROUP_BACKGROUND_SETTINGS, KEY_BG_FILE_PATH, "").toString();
    _bgSettings.radius = loadSetting(GROUP_BACKGROUND_SETTINGS, KEY_BG_RADIUS, 0).toInt();

    return true;
}

bool AppConfig::loadSettings()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    _playbackSettings.smartTiming = loadSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_SMART_TIMING, false).toBool();
    _playbackSettings.timelySetting = loadSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_TIMELY_SETTING, false).toBool();
    _playbackSettings.pauseTiming = loadSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_PAUSE_TIMING, false).toBool();
    _playbackSettings.noSwitchTime = loadSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_NO_SWITCH_TIME, false).toBool();
    _playbackSettings.hideWhenNotTiming = loadSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_HIDE_NOT_TIMING, false).toBool();
    _playbackSettings.dualScreenDisplay = loadSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_DUAL_SCREEN, false).toBool();

    return true;
}

bool AppConfig::saveSettings() const
{
    if (!this->settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    saveSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_SMART_TIMING, _playbackSettings.smartTiming);
    saveSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_TIMELY_SETTING, _playbackSettings.timelySetting);
    saveSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_PAUSE_TIMING, _playbackSettings.pauseTiming);
    saveSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_NO_SWITCH_TIME, _playbackSettings.noSwitchTime);
    saveSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_HIDE_NOT_TIMING, _playbackSettings.hideWhenNotTiming);
    saveSetting(GROUP_PLAYBACK_SETTINGS, KEY_PLAYBACK_DUAL_SCREEN, _playbackSettings.dualScreenDisplay);

    return true;
}

bool AppConfig::loadTimeoutAction()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;  // 返回默认的 TimeoutAction
    }

    // 从配置中加载超时动作类型和屏幕操作类型
    _timeoutAction.actionType = static_cast<TimeoutActionType>(loadSetting(GROUP_TIMEOUT_ACTION_SETTINGS, KEY_TIMEOUT_ACTION_TYPE, static_cast<int>(TimeoutActionType::TimeoutCount)).toInt());
    _timeoutAction.screenAction = static_cast<ScreenAction>(loadSetting(GROUP_TIMEOUT_ACTION_SETTINGS, KEY_TIMEOUT_SCREEN_ACTION, static_cast<int>(ScreenAction::SemiTransparent)).toInt());

    // 返回构造的 TimeoutAction 对象
    return true;
}

bool AppConfig::saveTimeoutAction() const
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    // 保存超时动作类型和屏幕操作类型
    saveSetting(GROUP_TIMEOUT_ACTION_SETTINGS, KEY_TIMEOUT_ACTION_TYPE, static_cast<int>(_timeoutAction.actionType));
    saveSetting(GROUP_TIMEOUT_ACTION_SETTINGS, KEY_TIMEOUT_SCREEN_ACTION, static_cast<int>(_timeoutAction.screenAction));

    return true;
}

bool AppConfig::saveSoundSettings() const
{
    if (!this->settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    // 保存每个 SoundInfo 结构体的成员
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_START_FILE_PATH, _soundSettings.start.soundFilePath);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_START_ENABLED, _soundSettings.start.isSoundEnabled);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_START_FLASHING, _soundSettings.start.isFlashing);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_START_TEXT_VISIBLE, _soundSettings.start.isTextVisible);

    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM1_FILE_PATH, _soundSettings.alarm1.soundFilePath);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM1_ENABLED, _soundSettings.alarm1.isSoundEnabled);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM1_FLASHING, _soundSettings.alarm1.isFlashing);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM1_TEXT_VISIBLE, _soundSettings.alarm1.isTextVisible);

    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM2_FILE_PATH, _soundSettings.alarm2.soundFilePath);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM2_ENABLED, _soundSettings.alarm2.isSoundEnabled);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM2_FLASHING, _soundSettings.alarm2.isFlashing);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM2_TEXT_VISIBLE, _soundSettings.alarm2.isTextVisible);

    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM3_FILE_PATH, _soundSettings.alarm3.soundFilePath);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM3_ENABLED, _soundSettings.alarm3.isSoundEnabled);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM3_FLASHING, _soundSettings.alarm3.isFlashing);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM3_TEXT_VISIBLE, _soundSettings.alarm3.isTextVisible);

    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TIMEOUT_FILE_PATH, _soundSettings.timeout.soundFilePath);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TIMEOUT_ENABLED, _soundSettings.timeout.isSoundEnabled);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TIMEOUT_FLASHING, _soundSettings.timeout.isFlashing);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TIMEOUT_TEXT_VISIBLE, _soundSettings.timeout.isTextVisible);

    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_END_FILE_PATH, _soundSettings.end.soundFilePath);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_END_ENABLED, _soundSettings.end.isSoundEnabled);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_END_FLASHING, _soundSettings.end.isFlashing);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_END_TEXT_VISIBLE, _soundSettings.end.isTextVisible);

    // Global sound controls
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_GLOBAL_MUTED, _soundMuted);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_GLOBAL_VOLUME, _soundVolume);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TICK_ENABLE, _tickEnable);
    saveSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TICK_INTERVAL, _tickIntervalMs);

    return true;
}

bool AppConfig::loadSoundSettings()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;  // 返回默认构造的 SoundSettings
    }

    // 从配置文件中加载每个 SoundInfo 结构体的成员
    _soundSettings.start.soundFilePath = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_START_FILE_PATH, "").toString();
    _soundSettings.start.isSoundEnabled = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_START_ENABLED, true).toBool();
    _soundSettings.start.isFlashing = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_START_FLASHING, false).toBool();
    _soundSettings.start.isTextVisible = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_START_TEXT_VISIBLE, true).toBool();

    _soundSettings.alarm1.soundFilePath = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM1_FILE_PATH, "").toString();
    _soundSettings.alarm1.isSoundEnabled = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM1_ENABLED, true).toBool();
    _soundSettings.alarm1.isFlashing = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM1_FLASHING, false).toBool();
    _soundSettings.alarm1.isTextVisible = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM1_TEXT_VISIBLE, true).toBool();

    _soundSettings.alarm2.soundFilePath = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM2_FILE_PATH, "").toString();
    _soundSettings.alarm2.isSoundEnabled = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM2_ENABLED, true).toBool();
    _soundSettings.alarm2.isFlashing = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM2_FLASHING, false).toBool();
    _soundSettings.alarm2.isTextVisible = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM2_TEXT_VISIBLE, true).toBool();

    _soundSettings.alarm3.soundFilePath = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM3_FILE_PATH, "").toString();
    _soundSettings.alarm3.isSoundEnabled = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM3_ENABLED, true).toBool();
    _soundSettings.alarm3.isFlashing = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM3_FLASHING, false).toBool();
    _soundSettings.alarm3.isTextVisible = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_ALARM3_TEXT_VISIBLE, true).toBool();

    _soundSettings.timeout.soundFilePath = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TIMEOUT_FILE_PATH, "").toString();
    _soundSettings.timeout.isSoundEnabled = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TIMEOUT_ENABLED, true).toBool();
    _soundSettings.timeout.isFlashing = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TIMEOUT_FLASHING, false).toBool();
    _soundSettings.timeout.isTextVisible = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TIMEOUT_TEXT_VISIBLE, true).toBool();

    _soundSettings.end.soundFilePath = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_END_FILE_PATH, "").toString();
    _soundSettings.end.isSoundEnabled = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_END_ENABLED, true).toBool();
    _soundSettings.end.isFlashing = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_END_FLASHING, false).toBool();
    _soundSettings.end.isTextVisible = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_END_TEXT_VISIBLE, true).toBool();

    // Global sound controls
    _soundMuted = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_GLOBAL_MUTED, false).toBool();
    _soundVolume = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_GLOBAL_VOLUME, 100).toInt();
    _tickEnable = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TICK_ENABLE, false).toBool();
    _tickIntervalMs = loadSetting(GROUP_SOUND_SETTINGS, KEY_SOUND_TICK_INTERVAL, 1000).toInt();

    return true;
}

bool AppConfig::saveUserInfoSettings() const
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }
    // 保存用户信息中的字段
    saveSetting(GROUP_APP_SETTINGS, KEY_APP_MAC_ADDRESS, _userInfo.macAddress);
    saveSetting(GROUP_APP_SETTINGS, KEY_APP_PERMISSION_LEVEL, static_cast<int>(_userInfo.permissionLevel));  // 保存权限等级
    saveSetting(GROUP_APP_SETTINGS, KEY_APP_ACTIVATION_DURATION, _userInfo.activationDuration);  // 保存激活时长
    saveSetting(GROUP_APP_SETTINGS, KEY_APP_SN, _userInfo.serialNumber);  // 保存SN号

    return true;
}

bool AppConfig::loadUserInfoSettings()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    // 从配置中加载用户信息字段
    _userInfo.macAddress = loadSetting(GROUP_APP_SETTINGS, KEY_APP_MAC_ADDRESS, "").toString();
    _userInfo.permissionLevel = static_cast<PermissionLevel>(loadSetting(GROUP_APP_SETTINGS, KEY_APP_PERMISSION_LEVEL, static_cast<int>(PermissionLevel::Guest)).toInt());
    _userInfo.activationDuration = loadSetting(GROUP_APP_SETTINGS, KEY_APP_ACTIVATION_DURATION, 0).toInt();
    _userInfo.serialNumber = loadSetting(GROUP_APP_SETTINGS, KEY_APP_SN, "").toString();

    return true;
}

bool AppConfig::saveTimeFormatSettings() const
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }
    // 保存用户信息中的字段
    saveSetting(GROUP_FORMAT_TYPE_SETTINGS, KEY_FORMAT_TYPE, static_cast<int>(_timeFormat));

    return true;
}

bool AppConfig::loadTimeFormatSettings()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }

    // 从配置中加载用户信息字段
    _timeFormat = static_cast<TimeFormat>(loadSetting(GROUP_FORMAT_TYPE_SETTINGS, KEY_FORMAT_TYPE, 2).toInt()) ;
    return true;
}

QByteArray AppConfig::encrypt(const QByteArray &data) const
{
    QByteArray encryptedData = data;
    for (int i = 0; i < data.size(); ++i) {
        encryptedData[i] = data[i] ^ encryptionKey[i % encryptionKey.size()];
    }
    return encryptedData.toBase64();
}

QByteArray AppConfig::decrypt(const QByteArray &data) const
{
    QByteArray encryptedData = QByteArray::fromBase64(data);
    QByteArray decryptedData = encryptedData;
    for (int i = 0; i < encryptedData.size(); ++i) {
        decryptedData[i] = encryptedData[i] ^ encryptionKey[i % encryptionKey.size()];
    }
    return decryptedData;
}

// ========== Screenshot settings ==========
bool AppConfig::saveScreenshotSettings() const
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }
    saveSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_DEFAULT_SAVE_PATH, _screenshotConfig.getDefaultSavePath());
    saveSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_DEFAULT_FILE_NAME, _screenshotConfig.getDefaultFileName());
    saveSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_DEFAULT_FORMAT, _screenshotConfig.getDefaultFormat());
    saveSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_JPEG_QUALITY, _screenshotConfig.getJpegQuality());
    saveSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_AUTO_COPY, _screenshotConfig.isAutoCopyToClipboard());
    saveSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_AUTO_SAVE, _screenshotConfig.isAutoSave());
    return true;
}

bool AppConfig::loadScreenshotSettings()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }
    ScreenshotConfig cfg;
    cfg.setDefaultSavePath(loadSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_DEFAULT_SAVE_PATH, cfg.getDefaultSavePath()).toString());
    cfg.setDefaultFileName(loadSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_DEFAULT_FILE_NAME, cfg.getDefaultFileName()).toString());
    cfg.setDefaultFormat(loadSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_DEFAULT_FORMAT, cfg.getDefaultFormat()).toString());
    cfg.setJpegQuality(loadSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_JPEG_QUALITY, cfg.getJpegQuality()).toInt());
    cfg.setAutoCopyToClipboard(loadSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_AUTO_COPY, cfg.isAutoCopyToClipboard()).toBool());
    cfg.setAutoSave(loadSetting(GROUP_SCREENSHOT_SETTINGS, KEY_SS_AUTO_SAVE, cfg.isAutoSave()).toBool());
    _screenshotConfig = cfg;
    return true;
}

// ========== [FDD-2025-03-015] Task Panel Settings ==========
bool AppConfig::saveTaskPanelSettings() const
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }
    saveSetting("UI", "TaskPanelExpanded", _taskPanelExpanded);
    return true;
}

bool AppConfig::loadTaskPanelSettings()
{
    if (!settings) {
        warningLog() << "Settings not initialized!";
        return false;
    }
    _taskPanelExpanded = loadSetting("UI", "TaskPanelExpanded", false).toBool();
    return true;
}
